//
//  JKPicCollectionView.swift
//  JKWeibo
//
//  Created by albert on 16/6/23.
//  Copyright © 2016年 albert. All rights reserved.
//  配图的collectionView

import UIKit
import SDWebImage

class JKPicCollectionView: UICollectionView {
    
    /// 流水布局
    @IBOutlet weak var flowLayout: UICollectionViewFlowLayout!
    /// collectionView宽度约束
    @IBOutlet weak var picCollectionViewWidthCons: NSLayoutConstraint!
    /// collectionView高度约束
    @IBOutlet weak var picCollectionViewHeightCons: NSLayoutConstraint!
    
    /** 模型数据 */
    var viewModel: JKStatusViewModel? {
        didSet {
            // 1.设置配图尺寸
            let (itemSize, collectionViewSize) = calculateSize()
            // item的尺寸不能为0
            if itemSize != CGSizeZero {
                flowLayout.itemSize = itemSize
            }
            picCollectionViewHeightCons.constant = collectionViewSize.height
            picCollectionViewWidthCons.constant = collectionViewSize.width
            
            // 2.更新配图
            reloadData()
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        registerNib(UINib(nibName: "JKHomePictureCell", bundle: nil), forCellWithReuseIdentifier: "pictureCell")
        
        self.dataSource = self
        self.delegate = self
    }
    
    //MARK: 内部控制方法
    /** 计算cell和collectionView的尺寸 */
    private func calculateSize() -> (CGSize, CGSize) {
        /*
         没有配图: cell = zero, collectionview = zero
         一张配图: cell = image.size, collectionview = image.size
         四张配图: cell = {90, 90}, collectionview = {2*w+m, 2*h+m}
         其他张配图: cell = {90, 90}, collectionview =
         */
        let count = viewModel?.thumbnail_pic_urls?.count ?? 0
        if count == 0 {
            return (CGSizeZero, CGSizeZero)
        }
        
        
        // 会崩溃，image可能为nil，所以守护一下
        if count == 1 {
            if let key = viewModel?.thumbnail_pic_urls?.first?.absoluteString {
                guard let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key) else {
                    return (CGSizeZero, CGSizeZero)
                }
                return (image.size, image.size)
            }
        }
        
        // 暂时写死为90
        let imageWidth: CGFloat = 90
        let imageHeight: CGFloat = 90
        let imageMargin: CGFloat = 10
        
        if count == 4 {
            let col = 2
            let row = col
            // 宽度 = 图片的宽度 * 列数 + (列数 - 1) * 间隙
            let width = imageWidth * CGFloat(col) + CGFloat(col - 1) * imageMargin
            // 高度 = 图片的高度 * 行数 + (行数 - 1) * 间隙
            let height = imageHeight * CGFloat(row) + CGFloat(row - 1) * imageMargin
            return (CGSize(width: imageWidth, height: imageHeight), CGSize(width: width, height: height))
        }
        
        let col = 3
        let row = (count - 1) / col + 1
        // 宽度 = 图片的宽度 * 列数 + (列数 - 1) * 间隙
        let width = imageWidth * CGFloat(col) + CGFloat(col - 1) * imageMargin
        // 高度 = 图片的高度 * 行数 + (行数 - 1) * 间隙
        let height = imageHeight * CGFloat(row) + CGFloat(row - 1) * imageMargin
        return (CGSize(width: imageWidth, height: imageHeight), CGSize(width: width, height: height))
    }
}

// MARK: - 数据源和代理
extension JKPicCollectionView : UICollectionViewDataSource,UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
        return viewModel?.thumbnail_pic_urls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("pictureCell", forIndexPath: indexPath) as! JKHomePictureCell
        
        cell.bMiddleUrl = viewModel?.bmiddlePicUrls![indexPath.item]
        cell.picUrl = viewModel!.thumbnail_pic_urls![indexPath.item]
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        // 发通知，由主页控制器弹出配图浏览器（控制器），告诉控制器哪些图片需要展示，当前应展示哪一张
        NSNotificationCenter.defaultCenter().postNotificationName(JKShowPicBrowserNotification, object: self, userInfo: [JKThumbPicUrlsKey : viewModel!.thumbnail_pic_urls!, JKBmiddlePicUrlsKey : viewModel!.bmiddlePicUrls!, JKIndexPathKey : indexPath])
    }
}

extension JKPicCollectionView: JKPresentManagerDelegate {
    /** 用于获取点击图片在图片浏览器中的最终frame */
    func browserPresentationControllerReloadData(browserPresentationController: JKPresentManager){
        reloadData()
    }
    
    /** 用于创建一个和点击图片一模一样的UIImageView */
    func browserPresentationControllerWillShowImageView(browserPresentationController: JKPresentManager, collectionViewCellIndex: NSIndexPath) -> UIImageView{
        
        // 1.创建一个新的UIImageView
        let imageView = UIImageView()
        // 设置内容模式
        imageView.contentMode = UIViewContentMode.ScaleAspectFill
        imageView.clipsToBounds = true
        
        // 2.设置imageView的图片为当前点击的图片
        let cell = cellForItemAtIndexPath(collectionViewCellIndex) as! JKHomePictureCell
        
        let key = viewModel?.bmiddlePicUrls![collectionViewCellIndex.item].absoluteString
        if let image =  SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key) {
            imageView.image = image
            
        }else {
            imageView.image = cell.pictureImageView.image
        }
        
        // 3.返回
        return imageView
    }
    
    /** 用于获取点击的图片相对于keyWindow的frame */
    func browserPresentationControllerWillFromFrame(browserPresentationController: JKPresentManager, collectionViewCellIndex: NSIndexPath) -> CGRect {
        
        // 1.拿到被点击的cell
        let cell = cellForItemAtIndexPath(collectionViewCellIndex) as! JKHomePictureCell
        
        // 2.将被点击的cell的坐标系从collectionview转换到keywindow
        let frame = convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        
        // 3.返回
        return frame
    }
    
    /** 用于获取点击图片在图片浏览器中的最终frame */
    func browserPresentationControllerWillToframe(browserPresentationController: JKPresentManager, collectionViewCellIndex: NSIndexPath) -> CGRect {
        
        // 1.拿到被点击的cell
        let cell = cellForItemAtIndexPath(collectionViewCellIndex) as! JKHomePictureCell
        
        // 2.拿到被点击的图片
        let image = cell.pictureImageView.image!
        
        // 3.返回
        return setupPicture(image)
    }
    
    /** 设置图片尺寸和位置 */
    private func setupPicture(image: UIImage) -> CGRect {
        let scale = image.size.width / image.size.height
        let imageWidth = JKScreenW
        let imageHeight = imageWidth / scale
        
        // 3.计算顶部和底部内边距
        var offsetY: CGFloat = 0
        
        // 4.设置图片位置
        if imageHeight < JKScreenH { // 计算后的图片高度 < 屏幕高度
            offsetY = (JKScreenH - imageHeight) * 0.5
        }
        
        return CGRect(x: 0, y: offsetY, width: imageWidth, height: imageHeight)
    }
}

class JKHomePictureCell: UICollectionViewCell {
    
    /// cell图片
    @IBOutlet weak var pictureImageView: UIImageView!
    /// GIF图标
    @IBOutlet weak var gifImageView: UIImageView!
    
    /** url */
    var bMiddleUrl: NSURL?
    
    /** url */
    var picUrl: NSURL? {
        didSet{
            if bMiddleUrl != nil {
                let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(bMiddleUrl!.absoluteString)
                
                if image != nil {
                    pictureImageView.image = image
                    // 2.控制GIF图标的显示和隐藏
                    if let gifFlag = picUrl?.absoluteString.lowercaseString.hasSuffix("gif") {
                        gifImageView.hidden = !gifFlag
                    }
                    return
                }
            }
            
            // 1.设置图片
            pictureImageView.sd_setImageWithURL(picUrl)
            
            // 2.控制GIF图标的显示和隐藏
            if let gifFlag = picUrl?.absoluteString.lowercaseString.hasSuffix("gif") {
                gifImageView.hidden = !gifFlag
            }
        }
    }
}
